var vk = new VkApi();
var albums = [];

// Ask before close or refresh
window.onbeforeunload = function closeEditorWarning() {
    return 'Загрузка фотографий будет прервана.'
};

window.onload = function onLoadEvents() {
    addCurrentUserNameToHTML();
};

/*
 * Error handler for directoryReader
 * */
function errorHandler(e) {
    var msg = '';
    switch (e.code) {
        case FileError.QUOTA_EXCEEDED_ERR:
            msg = 'QUOTA_EXCEEDED_ERR';
            break;
        case FileError.NOT_FOUND_ERR:
            msg = 'NOT_FOUND_ERR';
            break;
        case FileError.SECURITY_ERR:
            msg = 'SECURITY_ERR';
            break;
        case FileError.INVALID_MODIFICATION_ERR:
            msg = 'INVALID_MODIFICATION_ERR';
            break;
        case FileError.INVALID_STATE_ERR:
            msg = 'INVALID_STATE_ERR';
            break;
        default:
            msg = 'Unknown Error';
            break;
    }
    console.log(msg);
}

/*
 * Get selected by user privacy level
 * */
function getSelectedPrivacyLevel() {
    return $('#privacy').find(":selected").attr('value');
}

/*
 * Get selected by user comment privacy level
 * */
function getSelectedCommentPrivacyLevel() {
    return $('#comment_privacy').find(":selected").attr('value');
}

function getSelectedAlbumId() {
    return $('.add-to-album select').find(":selected").attr('album_id');
}

function getSelectedAlbumName() {
    return $('.add-to-album select').find(":selected").text();
}

/*
 * Check file type
 * */
function isFileTypeAllowed(fileName) {
    var ext = fileName.substr(fileName.lastIndexOf('.') + 1);
    switch (ext.toLowerCase()) {
        case 'jpg':
        case 'bmp':
        case 'png':
        case 'gif':
        case 'jpeg':
            return true;
            break;
        default:
            return false;
    }
}

function addAlbumInfo(albumId, photoCount) {
    albums.push({"albumId": albumId, "total": photoCount, "uploaded": 0});
}

function addOneUploadedToAlbum(albumId) {
    albums.forEach(function (album) {
        if (album.albumId == albumId) album.uploaded += 1;
    })
}

function getAlbumProgressPercentage(albumId) {
    for (var i = 0; i < albums.length; i++) {
        if (albums[i].albumId == albumId) {
            return Math.round(albums[i].uploaded / albums[i].total * 100);
        }
    }
    return undefined;
}


function filterNotAllowedFiles(files) {
    var filtered = [];
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        if (isFileTypeAllowed(file.name)) {
            filtered.push(file);
        } else {
            console.log("File is not allowed " + file.name)
        }
    }
    return filtered
}

function addToSelectedAlbum(entries) {
    var albumId = getSelectedAlbumId();
    var response = vk.getUploadServer(albumId);
    if (entries.length > 0) {
        addAlbumToAlbumsListHTML(getSelectedAlbumName(), albumId, entries.length);
        addAlbumInfo(albumId, entries.length);

        for (var i = 0; i < entries.length; i++) {
            processFile(entries[i], response.upload_url, response.aid);
        }
    } else {
        console.log("There is no supported files in dir: " + item.name);
    }
}

function processAlbum(entries, dirName) {
    if (entries.length > 0) {
        var privacy = getSelectedPrivacyLevel();
        var commentPrivacy = getSelectedCommentPrivacyLevel();
        var response = vk.createAlbum(dirName, privacy, commentPrivacy, entries.length, addAlbumToAlbumsListHTML);

        var albumId = response.aid;
        addAlbumInfo(albumId, entries.length);

        for (var i = 0; i < entries.length; i++) {
            processFile(entries[i], response.upload_url, albumId);
        }
    } else {
        console.log("There is no supported files in dir: " + dirName);
    }
}
function create(item) {
    if (item.isDirectory) {
        var result = [];
        var dirReader = item.createReader();
        var read = function () {
            dirReader.readEntries(function (entries) {
                if (!entries.length) {
                    processAlbum(result, item.name);
                } else {
                    result = result.concat(filterNotAllowedFiles(entries));
                    read();
                }
            }, errorHandler);
        };
        read();
    } else {
        console.log("Ignoring orphaned files")
    }
}
function add(item) {
    if (item.isDirectory) {
        var result = [];
        var dirReader = item.createReader();
        var read = function () {
            dirReader.readEntries(function (entries) {
                if (!entries.length) {
                    addToSelectedAlbum(result);
                } else {
                    result = result.concat(filterNotAllowedFiles(entries));
                    read();
                }
            }, errorHandler);
        };
        read();
    } else {
        console.log("Ignoring orphaned files")
    }
}


function traverseFileTree(item) {
    var isNew = $('.setting').is(':visible');
    if (isNew) {
        create(item);
    } else {
        add(item);
    }
}

function processFile(item, uploadUrl, albumId) {
    if (item.isFile) {
        // Get file and upload
        item.file(function (file) {
            vk.uploadPhoto(uploadUrl, file, albumId);
        });
    } else if (item.isDirectory) {
        console.log("Nested directories are ignored");
    }
}

function handleFileSelect(evt) {
    evt.stopPropagation();
    evt.preventDefault();

    this.classList.remove('hover');

    var items = evt.dataTransfer.items;
    for (var i = 0; i < items.length; i++) {
        var item = items[i].webkitGetAsEntry();
        if (item) {
            traverseFileTree(item);
        }
    }
}

function handleDragOver(evt) {
    evt.stopPropagation();
    evt.preventDefault();

    evt.dataTransfer.dropEffect = 'move';
    this.classList.add('hover');
}

function handleDragLeave(evt) {
    evt.stopPropagation();
    evt.preventDefault();

    this.classList.remove('hover');
}

// Setup the dnd listeners.
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
dropZone.addEventListener('dragleave', handleDragLeave, false);


$("#logout").click(function () {
    switchUserPrompt();
});

$('#add-tab, #create-tab, #download-tab').click(function () {
    $('#add-tab,#create-tab,#download-tab').removeClass('active');
    $(this).addClass('active');
});

$('#add-tab').click(function () {
    updateAlbumsInScope();
    $('.manual').hide();
    $('.setting').addClass('hidden');
    $('#download').addClass('hidden');
    $('.download-hint').addClass('hidden');
    $('.add-to-album').removeClass('hidden');
    $('#drop_zone').removeClass('hidden');
    clearAlbumList();

});

$('#download-tab').click(function () {
    updateAlbumsInScope();
    $('.manual').hide();
    $('.setting').addClass('hidden');
    $('#drop_zone').addClass('hidden');
    $('.add-to-album').removeClass('hidden');
    $('#download').removeClass('hidden');
    $('.download-hint').removeClass('hidden');
    clearAlbumList();

});

$('#create-tab').click(function () {
    $('.manual').hide();
    $('.add-to-album').addClass('hidden');
    $('.download-hint').addClass('hidden');
    $('#drop_zone').removeClass('hidden');
    $('.setting').removeClass('hidden');
    clearAlbumList();
});

$('.show-manual').click(function () {
    var manual = $('.manual');
    var showManualText = manual.is(':visible') ? 'Показать подробную инструкцию' : 'Скрыть подробную инструкцию';
    $(this).text(showManualText);
    manual.toggle();
});

$('#download').click(function () {
    var albumId = getSelectedAlbumId();
    var response = vk.getAlbumPhotos(albumId);
    var urlList = transformVkResponse(response);
    download(getSelectedAlbumName(), urlList.join("\r\n"));
});

$('.orbit').click(function () {
    chrome.tabs.create({url: "http://www.orbitdownloader.com/"});
});

function filterArray(arr, pattern) {
    var filtered = [], i = arr.length, re = new RegExp('^' + pattern);
    while (i--) {
        if (re.test(arr[i])) {
            filtered.push(arr[i]);
        }
    }
    return filtered;
}

function transformVkResponse(response) {
    var urlKey;
    var urlList = [], L = response.length;
    for (var i = 0; i < L; i++) {
        var photo = response[i];
        urlKey = getPhotoKey(photo);
        urlList.push(photo[urlKey]);
    }
    return urlList;
}

function getPhotoKey(photo) {
    var sizeList = ["src_xxxbig", "src_xxbig", "src_xbig", "src_big", "src_small", "src"], SL = sizeList.length;
    for (var j = 0; j < SL; j++) {
        if (sizeList[j] in photo) {
            return sizeList[j];
        }
    }
    return 'src';
}


function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);
    pom.click();
}

function clearAlbumList() {
    $('#list').empty();
}

function getAngularScope() {
    return angular.element($(".add-to-album")).scope();
}

function updateAlbumsInScope() {
    var scope = getAngularScope();
    if (vk.isTokenValid()) {
        scope.$apply(function () {
            scope.albums = vk.getAlbums();
        });
    } else {
        scope.$apply(function () {
            scope.albums = [];
        });
    }
}